#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<cstdlib>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<strings.h>
#include<pthread.h>
#include<string.h>
#include"Terminal.hpp"


using namespace std;

struct ThreadData
{
    struct sockaddr_in _server;
    int _sockfd;
};



void Usage(string proc)
{
    cout<<"Usage : "<<proc<<"serverip serverport"<<endl;
}

void *recv_message(void *args)
{
    //接发信息
    OpenTerminal();
    ThreadData *td = static_cast<ThreadData *>(args);
    char buffer[1024];
    while(true)
    {
        memset(buffer, 0, sizeof(buffer));
        //接收（回显）信息
        struct sockaddr_in temp;
        socklen_t lent = sizeof(temp);
        ssize_t s = recvfrom(td->_sockfd, buffer, 1023, 0, (struct sockaddr*)&temp, &lent);
        if(s>0)
        {
            buffer[s] = 0;
            cerr<<buffer<<endl;
        }
    }
}

void *send_message(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    string message;
    socklen_t len = sizeof(td->_server);
    while(true)
    {
         //发送信息
        cout<<"please Enter@ ";
        getline(cin, message);
        sendto(td->_sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&(td->_server), len);
    }
}

//./udpclient serverip serverport
int main(int argc, char *argv[])
{
    //打开网卡
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0); 
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    struct ThreadData td;

    td._sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(td._sockfd < 0)
    {
        cout<<"sockfd error"<<endl;
        return 1;
    }

    //准备资源（协议）
    bzero(&td._server, sizeof(td._server));
    td._server.sin_family = AF_INET;
    td._server.sin_port = htons(serverport);
    td._server.sin_addr.s_addr = inet_addr(serverip.c_str());


    //多线程解决阻塞不接收问题
    pthread_t recever, sender;
    pthread_create(&recever, nullptr, recv_message, &td);
    pthread_create(&sender, nullptr, send_message, &td);


    pthread_join(recever, nullptr);
    pthread_join(sender, nullptr);


    //关闭网卡
    close(td._sockfd);

    return 0;
}